package com.example.consumer;

import com.example.entity.Order;
import com.example.entity.OrderSort;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// 订单消费者
@Component
@Slf4j
public class OrderPriorityConsumer {
    // 注入已配置的ObjectMapper
    @Autowired
    private ObjectMapper objectMapper;
    
    @RabbitListener(queues = "order.priority.queue")
    public void processOrder(Message message, Channel channel) {
        try {
            String orderJson = new String(message.getBody());
            log.info("订单信息: {}", orderJson);

            // 获取消息优先级
            Integer priority = message.getMessageProperties().getPriority();

            log.info("开始处理订单 - 内容: {}, 优先级: {}, 处理时间: {}",
                    orderJson, priority,
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));

            // 模拟订单处理时间（根据优先级不同处理时间不同）
//            int processingTime = Math.max(1, 6 - priority); // 高优先级处理更快
            Thread.sleep(3 * 1000L);

            log.info("订单处理完成 - 内容: {}, 优先级: {}, 完成时间: {}",
                    orderJson, priority,
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            // 手动确认消息（deliveryTag：消息唯一标识；multiple：是否批量确认）
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理订单失败", e);
        }
    }
}